package com.codingfly;

import cn.hutool.crypto.digest.BCrypt;
import com.codingfly.entity.SysGroup;
import com.codingfly.entity.SysUser;
import com.codingfly.service.SysGroupService;
import com.codingfly.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Date;

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysGroupService sysGroupService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        addSysGroupRootNode();
        addAdminUser();
    }

    public void addSysGroupRootNode() {
        SysGroup sysGroup = sysGroupService.findRoot();
        if (sysGroup==null) {
            sysGroup = new SysGroup();
            sysGroup.setName("根节点");
            sysGroup.setCode("ROOT");
            sysGroup.setType(1);
            sysGroup.setOrderNo(1);
            sysGroupService.save(sysGroup);
            sysGroup.setFullPath(sysGroup.getId()+"");
            sysGroupService.save(sysGroup);
        }
    }

    public void addAdminUser() {
        SysUser user = sysUserService.findByUsername("admin");
        if (user==null) {
            user = new SysUser();
            user.setAuditTime(new Date());
            user.setUsername("admin");
            user.setPassword(BCrypt.hashpw("admin"));
            sysUserService.save(user);
        }
    }

}
